//
//  Client.cpp
//  xyz
//
//  Created by jorsun on 14-3-14.
//
//
#include "ConnClient.h"
#include "MessageProcessor.h"
ConnClient::ConnClient(void)
{
    client=new WebSocket();
    codec=new WebSocketCodec();
}
ConnClient::~ConnClient(void)
{
    if (client)
        client->close();
}//"ws://172.31.8.16:8002/websocket"
void ConnClient::connect(const char* url){
    if (!client->init(*this,url))
    {
        CC_SAFE_DELETE(client);
    }
}

// Delegate methods
void ConnClient::onOpen(cocos2d::extension::WebSocket* ws){
    CCLog("Websocket (%p) opened", ws);
    SessionMessage*  message= new SessionMessage(1);
    MessageProcessor::put(message);
}
void ConnClient::sendMessage(BaseMessage *message){
    codec->encode(message);
    client->send((unsigned char*)message->getBuffer(),message->getLength());
}

void ConnClient::onMessage(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::Data& data)
{
    if (!data.isBinary)
    {
        CCLog("data type is wrong");
    }
    else
    {
        char times[100] = {0};
        std::string binaryStr = "response bin msg: ";
        BaseMessage* message=codec->decode((unsigned char *)data.bytes);
        MessageProcessor::put(message);
    }
}

void ConnClient::onClose(cocos2d::extension::WebSocket* ws){
    client=NULL;
    CC_SAFE_DELETE(ws);
}

void ConnClient::onError(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::ErrorCode& error)
{
    CCLog("Error was fired, error code: %d", error);
}
